<?php
// +----------------------------------------------------------------------
// | SparkERP 优秀的进销存系统
// +----------------------------------------------------------------------
// | Copyright (c) 2022~2099 http://erp.sparkshop.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: NickBai  <1902822973@qq.com>
// +----------------------------------------------------------------------
namespace app\service\data;

use app\model\data\GoodsCate as GoodsCateModel;
use app\validate\data\GoodsCateValidate;
use think\db\exception\DbException;
use think\exception\ValidateException;

class GoodsCateService
{
    private GoodsCateModel $goodsCateModel;

    public function __construct(GoodsCateModel $goodsCateModel)
    {
        $this->goodsCateModel = $goodsCateModel;
    }

    /**
     * 获取商品分类列表
     * @param array $param
     * @return array
     */
    public function getList(array $param): array
    {
        try {
            $where = [];
            if (!empty($param['name'])) {
                $where[] = ['name', 'like', '%' . $param['name'] . '%'];
            }

            $list = $this->goodsCateModel->where($where)->order('sort desc,id asc')->select()->toArray();
            
            // 转换为树形结构
            $tree = buildTree($list);
            
            return dataReturn(0, 'success', ['list' => $tree]);
        } catch (\Exception $e) {
            return dataReturn(-1, $e->getMessage());
        }
    }

  
    /**
     * 添加商品分类
     * @param array $param
     * @return array
     */
    public function addGoodsCate(array $param): array
    {
        // 检验完整性
        try {
            validate(GoodsCateValidate::class)->check($param);
        } catch (ValidateException $e) {
            return dataReturn(-1, $e->getError());
        }
        
        // 检查同级分类名称是否重复
        $exists = $this->goodsCateModel->where([
            ['pid', '=', $param['pid']],
            ['name', '=', $param['name']]
        ])->find();
        
        if ($exists) {
            return dataReturn(-1, '同级分类名称已存在');
        }

        $param['create_time'] = now();
        $this->goodsCateModel->save($param);
        return dataReturn(0, '添加成功');
    }

    /**
     * 编辑商品分类
     * @param array $param
     * @return array
     */
    public function editGoodsCate(array $param): array
    {
        // 检验完整性
        try {
            validate(GoodsCateValidate::class)->check($param);
        } catch (ValidateException $e) {
            return dataReturn(-1, $e->getError());
        }
        
        // 检查同级分类名称是否重复
        $exists = $this->goodsCateModel->where([
            ['pid', '=', $param['pid']],
            ['name', '=', $param['name']],
            ['id', '<>', $param['id']]
        ])->find();
        
        if ($exists) {
            return dataReturn(-1, '同级分类名称已存在');
        }

        // 不能将自己设置为自己的子分类
        if ($param['pid'] == $param['id']) {
            return dataReturn(-1, '不能将自己设置为自己的子分类');
        }

        // 检查是否将自己的子分类设置为自己的父分类
        $childrenIds = $this->getChildrenIds($param['id']);
        if (in_array($param['pid'], $childrenIds)) {
            return dataReturn(-1, '不能将自己的子分类设置为自己的父分类');
        }

        $param['update_time'] = date('Y-m-d H:i:s');
        
        $this->goodsCateModel->where('id', $param['id'])->update($param);
        return dataReturn(0, '编辑成功');
    }

    /**
     * 删除商品分类
     * @param int $id
     * @return array
     */
    public function delGoodsCate(int $id): array
    {
        try {
            // 检查是否有子分类
            $children = $this->goodsCateModel->where('pid', $id)->find();
            if ($children) {
                return dataReturn(-1, '请先删除子分类');
            }

            // TODO: 检查是否有关联商品，如果有则不能删除

            $this->goodsCateModel->where('id', $id)->delete();
            return dataReturn(0, '删除成功');
        } catch (\Exception $e) {
            return dataReturn(-1, $e->getMessage());
        }
    }

    /**
     * 获取所有子分类ID
     * @param int $pid
     * @return array
     */
    private function getChildrenIds(int $pid): array
    {
        $ids = [];
        $children = $this->goodsCateModel->where('pid', $pid)->select();
        foreach ($children as $child) {
            $ids[] = $child['id'];
            $ids = array_merge($ids, $this->getChildrenIds($child['id']));
        }
        return $ids;
    }

    /**
     * 获取分类选择树
     * @return array
     */
    public function getSelectTree(): array
    {
        try {
            $list = $this->goodsCateModel->field('id,pid,name')->order('sort desc,id asc')->select()->toArray();
            $tree = buildTree($list);
            return dataReturn(['list' => $tree]);
        } catch (\Exception $e) {
            return dataReturn(-1, $e->getMessage());
        }
    }

    }